from time import sleep

from qturboframe.lib.report.log import logger
from qturboframe.lib.utils.CustomError.custom_error import CustomError
from qturboframe.lib.webdriver.exceptions import SeleniumError
from qturboframe.public_ui.base_element import BaseElement


class Select(BaseElement):
    """hui的下拉框控件操作"""

    def __init__(self, element_para, father=None, timeout=5):
        super().__init__(element_para, father, timeout)
        class_list = self._element.get_attribute('class').split(' ')
        if 'h-select' not in class_list:
            self._element = self._element.find_element_by_attribute(
                'xpath', './ancestor::div[contains(@class, "h-select")]', timeout=self.timeout)

    def set_value_for_single(self, value, timeout=20):
        """
        hui单选下拉框选择

        :Args:
         - value: 选择项的文本
         - timeout: 超时时间，默认是20s

        :Example:
         - 例1: select.set_value_for_single('苹果')
         - 例2: select.set_value_for_single('苹果',timeout=5)
        """
        select_ul_class = r'h-select-dropdown-list'
        select_section = self._element.find_element_by_attribute(
            'css selector', 'div.h-select-selection')
        try:
            # 当元素被覆盖，则无法点击
            select_section.click()
        except Exception as e:
            self._driver.execute_script("arguments[0].click();", select_section)
        # self._element.find_element_by_attribute(
        #     'css selector', 'div.h-select-selection').secure_click()
        input_element = self._element.exist(
            'css selector', 'div.h-select-selection>input', timeout=0.1)
        if input_element:
            input_element.send_keys(value)
        select_div = self._element.exist(
            'css selector', 'div.h-select-dropdown', timeout=0.1)
        if not select_div:
            # select_div = self._driver.find_element_by_attribute(
            #     'css selector', 'body>div.h-select-dropdown', 'style:display: block;', timeout=self.timeout)
            select_div = self._driver.find_element_by_attribute(
                'xpath', "//body/div[contains(@class,'h-select-dropdown') and not(contains(@style,'display: none'))]",
                timeout=self.timeout)
        timeout1 = 0
        while timeout1 < timeout * 10:
            select_ul = select_div.exist('css selector', 'ul.' + select_ul_class, timeout=0.1)
            if select_ul.is_displayed():
                break
            timeout1 += 1
            sleep(0.1)
        else:
            raise SeleniumError(CustomError.Error_EQ03016000_Select_No_Data)
        select_ul.find_element_by_attribute(
            'tag name', 'li', 'text:' + value, timeout=self.timeout).secure_click()

    def set_value_for_multiple(self, value=['all'], timeout=20):
        """
        hui的多选下拉框选择

        :Args:
         - value: 选择项的文本集合
         - timeout: 超时时间，默认是20s

        :Example:
         - 例1: select.set_value_for_multiple(['香蕉','苹果','葡萄'])
         - 例2: select.set_value_for_multiple(['香蕉','苹果','葡萄'], 5)
        """
        select_ul_class = r'h-select-dropdown-list'
        # 先全部清空
        self.clear_for_multiple()
        # 弹出下拉框
        self._element.find_element_by_attribute(
            'css selector', 'div.h-select-selection', timeout=self.timeout).secure_click()
        select_div = self._element.exist(
            'css selector', 'div.h-select-dropdown', timeout=0.1)
        if not select_div:
            select_div = self._driver.find_element_by_attribute(
                'css selector', 'div.h-select-dropdown', 'style:display: block;', timeout=self.timeout)
        timeout1 = 0
        while timeout1 < timeout * 10:
            select_ul = select_div.exist('css selector', 'ul.' + select_ul_class, timeout=0.1)
            if select_ul:
                if select_ul.is_displayed():
                    break
            timeout1 += 1
            sleep(0.1)
        else:
            raise SeleniumError(CustomError.Error_EQ03016000_Select_No_Data)
        if len(value) == 1 and value[0] == 'all':
            select_lis = select_ul.find_elements_by_attribute('tag name', 'li', timeout=self.timeout)
            for li in select_lis:
                li.find_element_by_attribute('css selector:', 'span.h-checkbox',
                                             timeout=self.timeout).secure_click()
        else:
            for text in value:
                select_li = select_ul.find_element_by_attribute('tag name', 'li', 'text:' + text,
                                                                timeout=self.timeout)
                select_li.find_element_by_attribute(
                    'css selector', 'span.h-checkbox', timeout=self.timeout).secure_click()

    def clear_for_single(self):
        """
        hui单选下拉框清除选项值

        :Example:
         - 例: select.clear_for_single()
        """
        self._element.move_to()
        self._element.find_element_by_attribute(
            'css selector', 'div.h-select-selection>i.h-icon-close',
            timeout=self.timeout).secure_click()

    def clear_for_multiple(self):
        """
        hui多选下拉框清除选项值

        :Example:
         - 例: select.clear_for_multiple()
        """
        data_divs = self._element.find_elements_by_attribute(
            'css selector', 'div.h-select-selection>div.h-tag', timeout=1)
        if len(data_divs) > 0:
            data_divs[0].find_element_by_attribute(
                'css selector', 'i.h-icon-close', timeout=self.timeout).secure_click()
            self.clear_for_multiple()

    def is_default_for_single(self, value):
        """
        检查hui单选下拉框默认值

        :Args:
         - value: 待检查的选项值

        :Returns:
            匹配返回True，否则返回False

        :Example:
         - 例: select.is_default_for_single('香蕉')
        """
        span_value = self._element.find_element_by_attribute(
            'css selector', 'div.h-select-selection>span.h-select-selected-value', timeout=0.1)
        text = span_value.text
        if text:
            if value == text:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        span_default = self._element.exist(
            'css selector', 'div.h-select-selection>span.h-select-placeholder', timeout=0.1)
        if span_default:
            text = span_default.text
            if value == text:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        else:
            logger.error('没有默认值！')
            return False

    def is_default_for_multiple(self, value):
        """
        检查hui多选下拉框默认值

        :Args:
         - value: 待检查的选项值

        :Returns:
            匹配返回True，否则返回False

        :Example:
         - 例: select.is_default_for_multiple('香蕉,苹果,葡萄')
        """
        span_value_list = self._element.find_elements_by_attribute(
            'css selector', 'div.h-select-selection>div.h-tag>span.h-tag-text', timeout=0.1)
        if span_value_list:
            for span_value in span_value_list:
                text = span_value.text
                for va in value:
                    if va == text:
                        break
                else:
                    logger.error('默认值不匹配！')
                    return False
            else:
                return True
        span_default = self._element.exist(
            'css selector', 'div.h-select-selection>span.h-select-placeholder', timeout=0.1)
        if span_default:
            text = span_default.text
            if value[0] == text:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        else:
            logger.error('没有默认值！')
            return False

    def is_nonnull(self):
        '''
        检查hui下拉框是否有非空属性

        :Returns:
            非空返回True，否则返回False

        :Example:
         - 例: select.is_nonnull()
        '''
        self._element.focus()
        form_item = self._element.find_element_by_attribute(
            'xpath', './ancestor::div[contains(@class, "h-form-item-content")]/'
                     'parent::div[contains(@class, "h-form-item")]', timeout=self.timeout)
        item_class_list = form_item.get_attribute('class').split(' ')
        if 'h-form-item-required' in item_class_list:
            return True
        else:
            return False

    def check_default_for_single(self, value):
        """
        检查hui单选下拉框默认值

        :Args:
         - value: 待检查的选项值

        :Raises:
            SeleniumError: 下拉框的默认值校验不通过

        :Example:
         -例: select.check_default_for_single('香蕉')
        """
        if not self.is_default_for_single(value):
            message = '下拉框的默认值校验不通过！'
            raise SeleniumError(CustomError.Error_EQ03016001_Select_Verify_Fail, message)

    def check_default_for_multiple(self, value):
        """
        检查hui多选下拉框默认值

        :Args:
         - value: 待检查的选项值

        :Raises:
            SeleniumError: 下拉框的默认值校验不通过

        :Example:
         - 例: select.check_default_for_multiple('香蕉,苹果,葡萄')
        """
        if not self.is_default_for_multiple(value):
            message = '下拉框的默认值校验不通过！'
            raise SeleniumError(CustomError.Error_EQ03016001_Select_Verify_Fail, message)

    def check_nonnull(self):
        '''
        检查hui下拉框是否有非空属性

        :Raises:
            SeleniumError: 下拉框的非空校验不通过

        :Example:
         - 例: select.check_nonnull()
        '''
        if not self.is_nonnull():
            message = '下拉框的非空校验不通过！'
            raise SeleniumError(CustomError.Error_EQ03016001_Select_Verify_Fail, message)
